package com.hunktimes.wholesale.ui.tabs.category

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gyf.immersionbar.ImmersionBar
import com.hunktimes.wholesale.net.model.FakeCategory
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.base.BaseMainFragment
import com.hunktimes.wholesale.databinding.FragmentCategoryBinding
import com.hunktimes.wholesale.extension.setImageUrl
import com.hunktimes.wholesale.mock.categoryModels
import com.hunktimes.wholesale.net.model.CategoryTag
import com.hunktimes.wholesale.util.L
import com.hunktimes.wholesale.util.ToastUtil

class CategoryFragment : BaseMainFragment(R.layout.fragment_category) {

    private val categoryViewModel: CategoryViewModel by viewModels<CategoryViewModel>()

    lateinit var viewBinding: FragmentCategoryBinding


    val exitInterceptor = ExitInterceptor()

    inner class ExitInterceptor : OnBackPressedCallback(true) {
        var LAST_BACKPRESS_TIMESTAMP: Long = -1L
        override fun handleOnBackPressed() {
            if (System.currentTimeMillis() - LAST_BACKPRESS_TIMESTAMP > 1500) {
                L.d("GoodsFragment ExitInterceptor 返回键间隔->大于<-1.5s")
                ToastUtil.showSimpleToast(getString(R.string.toast_exit))
                LAST_BACKPRESS_TIMESTAMP = System.currentTimeMillis()
            } else {
                isEnabled = false
                L.d("GoodsFragment ExitInterceptor 返回键间隔->小于<-1.5s")
                (requireActivity() as ComponentActivity).onBackPressedDispatcher.onBackPressed()
//                rootNavController.navigateUp()
            }
        }
    }


    /**
     * 1.在布局文件的根节点使用android:fitsSystemWindows="true"属性
     * 2.然后使用ImmersionBar时候必须指定状态栏颜色 及 开枪 DarkFont
     */
    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .init()
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = FragmentCategoryBinding.bind(view)
        viewBinding.btnTest.setOnClickListener {
            rootNavController.navigate(R.id.navigation_login)
        }
        viewBinding.btnTestAct.setOnClickListener {
            val parentFrag = requireParentFragment()//NavHostFragment
            L.d("GoodsFragmet requireParentFragment -> $parentFrag")
            val grandParentFrag = requireParentFragment().requireParentFragment()//MainFragment
            L.d("GoodsFragmet grandParentFrag -> $grandParentFrag")
            val act = requireActivity()//RootActivity
            L.d("GoodsFragmet requireActivity -> $act")
        }
        (requireActivity() as ComponentActivity).onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            exitInterceptor
        )

        initCategoryType()
        initCagetGoryList()


    }

    /**
     * 左側 分裂 標籤
     */
    val categoryTagAdapter = CategoryTagAdapter()
    fun initCategoryType() {
        val categoryTagLm = LinearLayoutManager(requireContext())
        categoryTagLm.orientation = LinearLayoutManager.VERTICAL
        viewBinding.categoryTagRcv.layoutManager = categoryTagLm
        viewBinding.categoryTagRcv.adapter = categoryTagAdapter

        val data = mutableListOf<CategoryTag>()
        for (i in 1..20) {
            data.add(CategoryTag(i == 1, "分類$i"))
        }
        categoryTagAdapter.data = data

        categoryTagAdapter.setOnItemClickListener { _, _, position ->
            categoryTagAdapter.selectPosition(
                position
            )
        }
    }

    /**
     * 右側 每個 大類 對應的 列表
     */
    val categorListAdapter = CategoryLisAdapter()
    fun initCagetGoryList() {
        val categoryLm = GridLayoutManager(requireContext(), 3)
        categoryLm.orientation = GridLayoutManager.VERTICAL

        viewBinding.categoryRcv.layoutManager = categoryLm
        viewBinding.categoryRcv.adapter = categorListAdapter

        //val data = mutableListOf<String>()
        val data = mutableListOf<FakeCategory>()
//        for (i in 1..20) {
//            data.add("分類詳情$i")
//        }
        repeat(20) {
            data.add(categoryModels.random())
        }
        categorListAdapter.data = categoryModels

        categorListAdapter.setOnItemClickListener { adapter, view, position ->
            rootNavController.navigate(R.id.navigation_category_search)
        }
    }
}

class CategoryTagAdapter :
    BaseQuickAdapter<CategoryTag, BaseViewHolder>(R.layout.item_category_tag) {
    override fun convert(holder: BaseViewHolder, item: CategoryTag) {
        holder.setText(R.id.item_category_tag_tv, item.categoryType)
        holder.itemView.isSelected = item.isSelect
    }

    fun selectPosition(postion: Int) {
        data.forEachIndexed { index, categoryTag ->
            categoryTag.isSelect = postion == index
        }
        notifyDataSetChanged()
    }
}

class CategoryLisAdapter : BaseQuickAdapter<FakeCategory, BaseViewHolder>(R.layout.item_category) {
    override fun convert(holder: BaseViewHolder, item: FakeCategory) {
        holder.setText(R.id.item_category_title_tv, item.name)
        val coverIv = holder.getView<ImageView>(R.id.item_category_cover_iv)
        coverIv.setImageUrl(item.imgUrl)
    }
}